package com.kidget;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

public class KidgetService extends Service {
  private static final String STUDENT_ID = "ac439205deaf69a1faf97d64787bf1d9bf69a87a_id";
  
  public static final String UPDATE_KIDGET = "updateKidget";
  private int widgetId;

  public KidgetService() {
  }

  @Override
  public void onStart(Intent intent, int startId) {
    Log.i(KidgetProvider.WIDGETTAG, "AM I HERE?");
  }


  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStart(intent, startId);
    Log.i(KidgetProvider.WIDGETTAG, "onStartCommand");
    updateStats(intent);
    stopSelf(startId);
    return START_STICKY;
  }

  
  private void updateStats(Intent intent) {
    Log.i(KidgetProvider.WIDGETTAG, "This is the intent " + intent);
    if (intent != null){
      String requestedAction = intent.getAction();
      Log.i(KidgetProvider.WIDGETTAG, "This is the action " + requestedAction);
      if (requestedAction != null && requestedAction.equals(UPDATE_KIDGET)){
        this.widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, 0);
        AppWidgetManager appWidgetMan = AppWidgetManager.getInstance(this);
        RemoteViews views = new RemoteViews(this.getPackageName(), R.layout.widgetlayout);
        views.setTextViewText(R.id.studentName, "Blah");
        appWidgetMan.updateAppWidget(widgetId, views);
        new NetworkCallTask().execute(this);
      }
    }
  }

  public static String getNameFromStudentBlob(JSONObject blob) throws JSONException {
    JSONObject name = blob.getJSONObject("name");
    return String.format("%s %s", 
        name.getString("firstName"),
        name.getString("lastSurname"));
  }
  
  public void updateCallback(String name) {
    System.err.printf("At updateCallback. Name [%s]", name);
    AppWidgetManager appWidgetMan = AppWidgetManager.getInstance(this);
    RemoteViews views = new RemoteViews(this.getPackageName(), R.layout.widgetlayout);
    views.setTextViewText(R.id.studentName, name);
    appWidgetMan.updateAppWidget(widgetId, views);
  }

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  private class NetworkCallTask extends AsyncTask<KidgetService, Integer, Long> {
    protected Long doInBackground(KidgetService... kidgetServices) {
      try {
        System.err.println("Making network call");
        String studentEndpoint = String.format("https://api.sandbox.slcedu.org/api/rest/v1/students/%s", STUDENT_ID);
        String studenJsonResponse = getJsonString(studentEndpoint);
        JSONObject studentBlob = new JSONObject(studenJsonResponse);
        String name = getNameFromStudentBlob(studentBlob);
        
        String attendanceEndpoint = String.format("https://api.sandbox.slcedu.org/api/rest/v1/attendances?studentId=%s", STUDENT_ID);
        // TODO: Update Attendance based on this.
                
        System.err.println(name);
        kidgetServices[0].updateCallback(name);
      } catch(Exception e) {
        System.err.println(e.toString());
      }
      return 0L;
    }

    private String getJsonString(String endpoint) throws IOException,
        ClientProtocolException, JSONException {
      HttpClient httpClient = new DefaultHttpClient();
      HttpGet get= new HttpGet(endpoint);
      get.setHeader("Content-Type", "application/vnd.slc+json");
      get.setHeader("Accept", "application/vnd.slc+json");
      get.setHeader("Authorization", "bearer t-5aaac369-24e3-4171-bcd1-6122e8ac519e");
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      String responseBody = httpClient.execute(get, responseHandler);
      return responseBody;

    }
  }
}